package com.wyp.design.pattern.creational.singleton.reflectattack;


import java.lang.reflect.Constructor;

/**
 * 懒汉式加载以及线程安全。使用静态内部类，让其他线程看不见初始化过程中的重排序。
 *
 * @author: yipeng.wang01@hand-china.com-25490
 * @TIME: 2020/1/2/13:40
 **/
public class LazySingletonStaticInnerClass {

    private static class InnerClassInstance {
        private static LazySingletonStaticInnerClass lazySingleton = new LazySingletonStaticInnerClass();
    }

    /**
     * @return
     */
    public static LazySingletonStaticInnerClass getInstance() {
        return InnerClassInstance.lazySingleton;
    }

    private LazySingletonStaticInnerClass() {
        if (InnerClassInstance.lazySingleton != null) {
            throw new RuntimeException("单例构造器禁止反射创建！");
        }
    }

    public static void main(String[] args) throws Exception {
        //使用反射进行创建对象
        Class<LazySingletonStaticInnerClass> innerClassClass = LazySingletonStaticInnerClass.class;
        //获取私有构造器
        Constructor<LazySingletonStaticInnerClass> constructor = innerClassClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        LazySingletonStaticInnerClass newInstance = constructor.newInstance();
        LazySingletonStaticInnerClass instance = LazySingletonStaticInnerClass.getInstance();

        System.out.println(newInstance);
        System.out.println(instance);
        System.out.println(newInstance == instance);
    }
}
